package com.tanhua.server.intercept;
import com.tanhua.domain.db.User;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class MyIntercept implements HandlerInterceptor {
    //   注入userInfoService对象 方便调用get方法
    @Autowired
    private UserInfoService userInfoService;
    //  注入ThreadLocalUtils对象
    @Autowired
    private ThreadLocalUtils threadLocalUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("来到了拦截器！");
//      获取请求头携带的token参数
        String token = request.getHeader("Authorization");
        if(StringUtils.isNotEmpty(token)){
            log.debug("获得的请求头token参数："+token);
        //获取请求路径
        log.debug("请求路径为：" + request.getRequestURL());
//      注入userServcie 对象 调用方法 传入token 返回一个user值
            User user = userInfoService.extensionOfTimeByToken(token);
            if(user==null){
//          如果令牌获取的值为null 那么就不放行
                response.setStatus(401);
                return false;
            }
//      将user值存入到Threadlocal中
            log.debug("threadLocalUtils开始存储对象:"+user);
            threadLocalUtils.setUser(user);
            return true;
        }
        response.setStatus(401);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
